﻿Imports System.Windows.Forms

Public Class mappingform
    Private myh As MySqlHandler
    Private wch As IWinccHandler
    Private tablemap As ewindt.DtTableMappingDataTable
    Private colmap As ewindt.DtColumnMappingDataTable
    Private log As ActivityLogger
    Private mapgrid As ewindt.DtMapRelationDataTable
    Private changed As Boolean
    Private currenttableindex As Integer
    Private currentarchiveindex As Integer
    Private processtableselection As Boolean = True
    Private processarchiveselection As Boolean = True
    Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Me.DialogResult = System.Windows.Forms.DialogResult.OK
        Me.Close()
    End Sub

    Private Sub Cancel_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Me.DialogResult = System.Windows.Forms.DialogResult.Cancel
        Me.Close()
    End Sub

    Private Sub mappingform_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        doLog("Exiting mapping definition", CINFO)
    End Sub

    Private Sub mappingform_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Timer1.Enabled = True
        Timer1.Start()
        log = ActivityLogger.getInstance
    End Sub

    Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Timer1.Stop()
        Timer1.Enabled = False
        doLog("Starting Mapping Definition", CINFO)
        loadMapping()
    End Sub
    Private Sub loadMapping()
        If (My.Settings.op_isdebug) Then
            wch = MockWinccHandler.getInstance
        Else
            wch = WinccHandler.getInstance
        End If
        myh = MySqlHandler.getInstance
        tablemap = myh.getTablesMapping
        colmap = myh.getColumnMapping
        If (IsNothing(mapgrid)) Then mapgrid = New ewindt.DtMapRelationDataTable
        dgmap.DataSource = mapgrid
    End Sub
   
    Private Sub cmbarchive_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbarchive.SelectedIndexChanged
        If (IsNothing(cmbarchive.SelectedItem)) Then Return
        'If (cmbarchive.SelectedItem.ToString = WinccConfig.ARCHIVE) Then
        loadArchiveMapping()
        'Else
        'loadAlarmMapping()
        'End If
    End Sub
    Private Sub loadArchiveMapping()
        doLog("Loading " + cmbarchive.SelectedItem.ToString + " Mapping", CINFO)
        Dim fil As String = tablemap.wincctablenameColumn.ColumnName + "='" + cmbarchive.SelectedItem.ToString + "'"
        Dim dt() As DataRow = tablemap.Select(fil)
        loadTableSelect(dt)
        doLog("Loading " + cmbarchive.SelectedItem.ToString + " Mapping done", CINFO)
    End Sub
    Private Sub loadArchiveMapping(ByVal selrow As DataRow)
        loadArchiveMapping()
        cmbtable.SelectedItem = selrow
    End Sub
    Private Sub loadAlarmMapping()
        Dim fil As String = tablemap.wincctablenameColumn.ColumnName + "='" + cmbarchive.SelectedItem.ToString + "'"
        Dim dt() As DataRow = tablemap.Select(fil)
        loadTableSelect(dt)
    End Sub
    Private Sub loadTableSelect(ByVal dt() As DataRow)
        'cmbtable.Items.Clear()
        'For Each r As DataRow In dt
        'cmbtable.Items.Add(r)
        'Next
        cmbtable.DataSource = dt
        cmbtable.DisplayMember = "mysqltablename"
        cmbtable.ValueMember = "ID"
    End Sub
    Private Sub doLog(ByVal msg As String, ByVal sev As Integer)
        Dim cm As String = ActivityLoggerConf.LOGLEVEL_INFO
        If (sev = COPE) Then cm = ActivityLoggerConf.LOGLEVEL_OPERATION
        If (sev = CERROR) Then cm = ActivityLoggerConf.LOGLEVEL_ERROR
        log.log(commons.MOD_MAPPING, msg, cm)
    End Sub
    Private Const CINFO As Integer = 1
    Private Const CERROR As Integer = 2
    Private Const COPE As Integer = 3

    Private Sub btnadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnadd.Click
        Dim tablename As String = InputBox("Please specify Mapping table name", commons.MOD_MAPPING)
        If (String.IsNullOrEmpty(tablename)) Then Return
        Dim r As ewindt.DtTableMappingRow = myh.addTableMapping(tablename, cmbarchive.SelectedItem)
        If (IsNothing(r)) Then
            commons.simpleMessage(commons.MOD_MAPPING, myh.Errors, vbInformation)
            Return
        End If
        tablemap = myh.getTablesMapping
        Dim n As ewindt.DtTableMappingRow = tablemap.NewDtTableMappingRow
        n.mysqltablename = r.mysqltablename
        n.mapstate = r.mapstate
        n.wincctablename = r.wincctablename
        n.id = r.id
        'tablemap.AddDtTableMappingRow(n)
        'tablemap.AcceptChanges()
        loadArchiveMapping(n)
    End Sub

    Private Sub cmbtable_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbtable.SelectedIndexChanged
        If (Not processtableselection) Then Return
        If (cmbtable.SelectedIndex < 0) Then Return
        If (IsNothing(cmbtable.SelectedItem)) Then Return

        If (changed) Then
            Dim ret = MsgBox("There are unsaved changes" + vbCrLf + "Do you to save these changes", vbYesNoCancel, "Mapping")
            If (ret = vbYes) Then
                'apply change
                applyMappingChange()
            ElseIf (ret = vbCancel) Then
                processtableselection = False
                cmbtable.SelectedIndex = currenttableindex
                processtableselection = True
                Return
            End If
        End If
        currenttableindex = cmbarchive.SelectedIndex
        Dim it As ewindt.DtTableMappingRow = CType(cmbtable.SelectedItem, ewindt.DtTableMappingRow)
        If (IsNothing(it)) Then Return
        If (cmbarchive.SelectedItem = WinccConfig.ARCHIVE) Then
            loadTagColumnMapping(it)
        Else
            loadAlarmColumnMapping(it)
        End If
    End Sub
    Private Sub loadAlarmColumnMapping(ByVal ra As ewindt.DtTableMappingRow)
        doLog("Loading Alarm Fields Values mapping for" + ra.mysqltablename, CINFO)
        Dim dt As ewindt.DtTagListDataTable = wch.getAlarmsField
        mapgrid.Clear()
        For Each r As ewindt.DtTagListRow In dt.Rows
            Dim n = mapgrid.NewDtMapRelationRow
            n.winccname = r.ValueName
            Dim rm = getMysqlMappingRow(ra.id, n.winccname)
            If (IsNothing(rm)) Then
                n.idcolmap = 0
                n.import = False
                n.mysqlname = ""
                n.idwccol = r.ValueID
            Else
                n.idcolmap = rm.id
                n.import = rm.imported
                n.mysqlname = rm.mycolname
                n.idwccol = rm.wincolid
            End If
            mapgrid.AddDtMapRelationRow(n)
        Next
        mapgrid.AcceptChanges()
    End Sub

    Private Sub loadTagColumnMapping(ByVal r As ewindt.DtTableMappingRow)
        'load all available tag
        doLog("Loading Tag Values mapping for" + r.mysqltablename, CINFO)
        loadWinccTag(r.id)
        doLog("Loading Tag Values mapping for" + r.mysqltablename + " done", CINFO)
        'map column
    End Sub
    Private Sub loadWinccTag(ByVal tm As Integer)
        Dim dt As ewindt.DtTagListDataTable = wch.listTag
        If (IsNothing(dt)) Then
            doLog("Unable to Fetch Tag list. Mapping will not be done", CERROR)
            commons.simpleMessage(commons.MOD_MAPPING, "Unable to Fetch Tag List." + vbCrLf + "Please Check Configuration", vbCritical)
            Return
        End If
        mapgrid.Clear()
        For Each r As ewindt.DtTagListRow In dt.Rows
            Dim n = mapgrid.NewDtMapRelationRow
            n.winccname = r.ValueName
            Dim rm = getMysqlMappingRow(tm, n.winccname)
            If (IsNothing(rm)) Then
                n.idcolmap = 0
                n.import = False
                n.mysqlname = ""
                n.idwccol = r.ValueID
            Else
                n.idcolmap = rm.id
                n.import = rm.imported
                n.mysqlname = rm.mycolname
                n.idwccol = rm.wincolid
            End If
            mapgrid.AddDtMapRelationRow(n)
        Next
        mapgrid.AcceptChanges()
    End Sub
    Private Function getMysqlMappingRow(ByVal mapid As Integer, ByVal wtag As String) As ewindt.DtColumnMappingRow
        If (IsNothing(colmap)) Then Return Nothing
        Dim filter As String = colmap.idtablemappingColumn.ColumnName + "=" + mapid.ToString + " and " + colmap.wincolnameColumn.ColumnName + "='" + wtag.Trim + "'"
        Dim ret() As DataRow = colmap.Select(filter)
        If (IsNothing(ret)) Then Return Nothing
        If (ret.Length <= 0) Then Return Nothing
        Dim lret As ewindt.DtColumnMappingRow = CType(ret(0), ewindt.DtColumnMappingRow)
        Return lret
    End Function
    Private Sub loadWinCCAlarm()
        

    End Sub

    Private Sub dgmap_CellBeginEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles dgmap.CellBeginEdit
        changed = True
    End Sub

    
    Private Sub btnclose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnclose.Click
        If (changed) Then
            Dim ret = MsgBox("There are unsaved changes." + vbCrLf + "Do you realy want to quit?", vbYesNo, "Mapping")
            If (ret = vbNo) Then Return
        End If
        doLog("Exiting Mapping", CINFO)
        Me.Close()
    End Sub

    Private Sub btnapply_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnapply.Click
        Me.Cursor = Cursors.AppStarting
        applyMappingChange()
        Me.Cursor = Cursors.Default
    End Sub
    Private Sub applyMappingChange()
        Dim it As ewindt.DtTableMappingRow = CType(cmbtable.SelectedItem, ewindt.DtTableMappingRow)
        Dim mapid As Integer = it.id
        Dim erm As String = ""
        For Each r As ewindt.DtMapRelationRow In mapgrid.Rows
            If (r.import) Then
                If (r.idcolmap > 0) Then
                    'update
                    If (Not myh.updateColMapping(r.idcolmap, r.mysqlname, r.winccname, r.idwccol)) Then
                        erm = erm + myh.Errors + vbCrLf
                    End If
                Else
                    'create
                    If (Not myh.addColMapping(mapid, r.mysqlname, r.winccname, r.idwccol)) Then
                        erm = erm + myh.Errors + vbCrLf
                    End If
                End If
            End If
        Next
        If (Not String.IsNullOrEmpty(erm)) Then
            commons.yesNoCancelMsg(commons.MOD_MAPPING, "Error occured when saving mapping" + erm)
        Else
            MsgBox("Mapping saved", vbInformation)
        End If
        changed = False
        colmap = myh.getColumnMapping
    End Sub

    Private Sub LinkLabel2_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel2.LinkClicked
        savedlg.ShowDialog()
        Dim filename As String = savedlg.FileName
        If (String.IsNullOrEmpty(filename)) Then Return
        doExport(filename)
        MsgBox("Export Done")
    End Sub
    Private Sub doExport(ByVal filename As String)
        Dim dts As New DataSet("mapexport")
        dts.Tables.Add(tablemap)
        dts.Tables.Add(colmap)
        dts.WriteXml(filename, XmlWriteMode.WriteSchema)
    End Sub

    Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
        opendlg.ShowDialog()
        Dim filename As String = opendlg.FileName
        If (String.IsNullOrEmpty(filename)) Then Return
        doImport(filename)
        cmbarchive.SelectedIndex = -1
        cmbtable.SelectedIndex = -1
        mapgrid.Clear()
        mapgrid.AcceptChanges()
        MsgBox("Import done")
    End Sub
    Private Sub doImport(ByVal filename As String)
        Dim dts As DataSet = New DataSet
        Try
            dts.ReadXml(filename)
            'tablemap = dts.Tables(Ewindt.DtTableMapping.TableName)
            tablemap.Clear()
            tablemap.Load(dts.Tables(Ewindt.DtTableMapping.TableName).CreateDataReader)
            colmap.Clear()
            colmap.Load(dts.Tables(Ewindt.DtColumnMapping.TableName).CreateDataReader)
            tablemap.AcceptChanges()
            colmap.AcceptChanges()
        Catch ex As Exception

        End Try
    End Sub

    Private Sub btnok_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnok.Click
        Me.Cursor = Cursors.AppStarting
        applyMappingChange()
        Me.Cursor = Cursors.Default
        Me.Close()
    End Sub
End Class
